#include "base/channel.h"
#include "base/log.h"

#include <unistd.h>
#include "base/channelpool.h"
namespace net_tools::base{

Channelpool::Channelpool(Epoll* epoll,int base_size)
  :epoll_(epoll)
{
  channel_free_vector.reserve(base_size);
  for(int count = 0;count < base_size;++count){
    Channel *channel_ = new Channel(epoll_);
    channel_free_vector.push_back(channel_);
  }
}
Channel* Channelpool::Get_Channel(int fd)
{
  if(channel_free_vector.empty()) [[unlikely]] { //small chance don't have free channel
//  if(channel_free_vector.empty()){
    for(int count = 0;count < _C::EACH_NEW_CHANNEL;++count){
      Channel *channel_ = new Channel(epoll_);
      channel_free_vector.push_back(channel_);
    }
  }
  Channel *channel_ = channel_free_vector.back();
  channel_free_vector.pop_back();
  channel_->Listenfd_init(fd);
  return channel_;
}
void Channelpool::Free_Channel(Channel* old_Channel)
{
  close(old_Channel->Get_listenfd());
  old_Channel->Set_close_callback(nullptr);
  old_Channel->Set_read_callback(nullptr);
  old_Channel->Set_write_callback(nullptr);
  channel_free_vector.push_back(old_Channel);
}

} // namespace net_tools::base